package controllers

import javax.inject.Inject

import play.api.libs.json.Json
import play.api.mvc._
import dao._
import models.Tables._

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.ExecutionContext.Implicits.global

class PhenotypeController @Inject()(cc:ControllerComponents,melonShapeDao: MelonShapeDao, sampleDao: SampleDao, umamiDao: UmamiDao) extends AbstractController(cc) {

  def toMelonShape = Action {
    Ok(views.html.phenotype.melonShape())
  }

  def toGm = Action {
    Ok(views.html.phenotype.gm())
  }

  def toUmami = Action {
    Ok(views.html.phenotype.umami())
  }

  def toUmami2015 = Action {
    Ok(views.html.phenotype.umami2015())
  }

  def toSample = Action {
    Ok(views.html.phenotype.sample())
  }

  def getAllMelonShapes = Action.async { implicit request =>
    melonShapeDao.selectAll.map { x =>
      val array = getArrayByMelonShapes(x)
      Ok(Json.toJson(array))
    }
  }

  def getAllUmamis = Action.async { implicit request =>
    umamiDao.selectByYear("2014").map { x =>
      val array = getArrayByUmamis(x)
      Ok(Json.toJson(array))
    }
  }

  def getAll2015Umamis = Action.async { implicit request =>
    umamiDao.selectByYear("2015").map { x =>
      val array = getArrayByUmamis(x)
      Ok(Json.toJson(array))
    }
  }

  def getAllSamples = Action.async { implicit request =>
    sampleDao.selectAll.map { x =>
      val array = getArrayBySamples(x)
      Ok(Json.toJson(array))
    }
  }

  def getArrayBySamples(x: Seq[SampleRow]) = {
    x.map { y =>
      Json.obj(
        "name" -> y.name, "character" -> y.character
      )
    }
  }

  def getArrayByMelonShapes(x: Seq[MelonshapeRow]) = {
    x.map { y =>
      val imageStr = if (y.image == "NA") "NA" else "<img src=" + routes.Assets.at("images/") + y.image + " style='max-width:100%'>"
      Json.obj(
        "name" -> y.name, "site" -> y.site, "kind" -> y.kind, "shape" -> y.shape, "image" -> imageStr
      )
    }
  }

  def getArrayByUmamis(x: Seq[UmamiRow]) = {
    x.map { y =>
      Json.obj(
        "accession" -> y.accession, "asp" -> y.asp, "thr" -> y.thr, "ser" -> y.ser, "glu" -> y.glu,
        "gly" -> y.gly, "ala" -> y.ala, "cys" -> y.cys, "val" -> y.`val`, "met" -> y.met, "ile" -> y.ile, "leu" -> y.leu,
        "tyr" -> y.tyr, "phe" -> y.phe, "gAba" -> y.gaba, "lys" -> y.lys, "his" -> y.his, "arg" -> y.arg, "pro" -> y.pro,
        "total" -> y.total
      )
    }
  }


}
